<template>
	<div class="main">
		 <div ref="stickyHeader">
            <div v-sticky>
                <navTop></navTop>
                <div style="background:#F4F7FD;padding-top:10px;">
                    <div class="searchlist">
                        <div style="display: flex;align-items: center;">
                            <span style="font-size:14px;color:#2A303B;">得分率：</span>
                            <div class="elinput" style="display: flex;align-items: center;">
                                <el-input 
                                    v-model="rateLeft" 
                                    style="width:80px;"
                                    @keypress.native="(e) => /[0-9]/.test(e.key) || e.preventDefault()"
                                    @input="val => handleStartInput(val, 'startdfscore')"
                                    :class="{ 'error-border': !isValidStart }"
                                    @change="handleStartChange"
                                ></el-input>
                                <b style="padding:0 8px;display: inline-block;">-</b>
                                <el-input 
                                    v-model="rateRight" 
                                    style="width:70px;"
                                    @keypress.native="(e) => /[0-9]/.test(e.key) || e.preventDefault()"
                                    @input="val => handleEndInput(val, 'endedfscore')"
                                    :class="{ 'error-border': !isValidEnd }"
                                    @change="handleEndChange"
                                ></el-input>
                            </div>
                            <el-select v-model="questionTypeName" placeholder="请选择题型" @click="questiontypeChange" clearable>
                                <el-option
                                v-for="item in difficultylist"
                                :key="item"
                                :label="item"
                                :value="item">
                                </el-option>
                            </el-select>
                            <!-- <el-select v-model="gradeId" placeholder="请选择预设难度" @focus="gradelistfocus" @change="gradelistchange" clearable>
                                <el-option
                                key="0"
                                label="全部"
                                value="0">
                                </el-option>
                                <el-option
                                v-for="item in gradelist"
                                :key="item.gradeId"
                                :label="item.name"
                                :value="item.gradeId">
                                </el-option>
                            </el-select> -->
                        </div>
                    </div>
                </div>
                <div style="background:#F4F7FD;padding-top:10px;">
                    <div class="searchlist">
                        <p class="titledata"><i>日常作业</i>{{$route.query.title}}（共{{questionarrylist.length}}题）</p>
                    </div>
                </div>
            </div>
            <div style="background:#F4F7FD;">
				<div class="questionbox" v-for="(item,index) in questionarrylist">
                    <div style="display: flex;justify-content:right;align-items: center;position:relative;height:50px;">
                        <h3 class="titlebox">
                            {{ item.questionInfo.length>1?'第'+item.questionInfo[0].questionNum.split('-')[0]+'题':item.questionInfo[0].questionNum }}
                        </h3>
                        <div class="boxcenterbutton">
                            <!-- <span @click="answerclick(index)">答案解析<i :class="answerclickindex==index?'el-icon-arrow-up hover':'el-icon-arrow-up'"></i></span>
                            <span @click="scoreclick(index)">得分明细<i :class="scoreclickindex==index?'el-icon-arrow-up hover':'el-icon-arrow-up'"></i></span> -->
                            <!-- <span>选中加练<i class="el-icon-circle-check"></i></span> --> 
                            <span @click="answerclick(index)">答案解析<i :class="{'hover': item.questionIshow}"></i></span>
                            <span @click="scoreclick(index)">得分明细<i :class="{'hover': item.questionScore}"></i></span>
                        </div>
                    </div>
                    <div style="padding:0 14px 24px;">
                            <div class="questionscore" style="padding:15px 0 15px;">
                                <div v-for="scoreaya in item.questionInfo" style="padding:5px 0">
                                    <span v-if="item.questionInfo.length>1" style="padding-right:10px;">题号：{{scoreaya.questionNum.split('-')[1]}}{{scoreaya.questionNum.split('-')[2]}}</span>
                                    <span>满分：<i>{{scoreaya.fullScore}}分</i></span>、
                                    <span>班平均分：<i>{{scoreaya.avgScore}}分</i></span>、
                                    <span>最高分：<i>{{scoreaya.maxScore}}分</i></span>、
                                    <span>最低分：<i>{{scoreaya.minScore}}分</i></span>、
                                    <span>班得分率：<i>{{scoreaya.scoreRate}}%</i></span>
                                </div>
                            </div>
                        <!-- 题干 -->
                        <div v-html="item.contentPageShow" style="font-size:12px;"></div>
                        <div v-if="item.optionPageShowList" style="font-size:12px;"><span v-for="(option,index) in item.optionPageShowList" style="display: flex;font-size:12px;">{{ index==0?'A':index==1?'B':index==2?'C':index==3?'D':index==4?'E':index==5?'F':'G' }}、<i v-html="option" style="font-style:normal;"></i></span></div>
                        <div style="font-size:12px;">
                            <div v-for="chil in item.children" >
                                <div v-html="chil.contentPageShow"></div>
                                <div v-if="item.questionIshow">
                                    <div style="display:flex;padding-top:25px;font-size:12px;" v-if="chil.answerPageShowList">
                                        <b style="color:rgb(79,204,248);font-size:12px;">【答案】</b><div v-for="answer in  chil.answerPageShowList" style="font-size:12px;"><div v-html="answer"></div></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- 答案解析 -->
                        <div v-show="item.questionIshow">
                            <div style="display:flex;padding-top:25px;" v-if="item.answerPageShowList">
                                <b style="color:rgb(79,204,248);font-size:12px;">【答案】</b><div v-for="answ in  item.answerPageShowList" style="font-size:12px;"><div v-html="answ"></div></div>
                            </div>
                            <div style="display:flex;padding-top:10px;">
                                <b style="color:rgb(79,204,248);font-size:12px;">【解析】</b><div v-html="item.analysisPageShow" style="font-size:12px;"></div>
                            </div>
                        </div>
                    </div>
                    <div class="boxulxd" v-show="item.questionScore">
                        <div  v-for="(people,index) in item.details">
                            <div style="font-size:14px;">{{ item.details.length<2?'':item.questionInfo[index].questionNum.split('-')[1]}}{{ item.details.length<2?'':item.questionInfo[index].questionNum.split('-')[2] }}</div>
                            <li v-for="pchil in people">{{pchil.scoreRange?pchil.scoreRange:'空'}}：<b v-for="(name,nameindex) in pchil.students">{{ name.name }}<i v-if="nameindex < pchil.students.length - 1">、</i></b>({{pchil.count}}人占{{pchil.percentage}}%)</li>
                        </div>
                    </div>
                </div>
            </div>
		</div>
	</div>
</template>

<script>
	import navTop from "../../components/homework/headtop.vue"
	import empty from '../../components/school/empty.vue'
    import {questionlist,questionlistuuid,questionlistscoreuuid,get} from '../../request/api.js'
	export default{
		data(){
			return{
                startdfscore:'',
                endedfscore:'',
                examType:'',
                gradeId:'',
                questionarrylist:[],
                questionUUids:[],
                isValidStart: true,
                isValidEnd: true,
                classifylist:[],
                difficultylist:[],
                rateLeft:undefined,
                rateRight:undefined,
                questionTypeName:'',
                scoreclickindex:-1,
                answerclickindex:-1,
                questionnewlist:[]
			}
		},
		mounted() {
			 this.questionbank()
             this.renderMathJax()
             this.$nextTick(() => {
                // 手动触发滚动事件，让指令重新计算位置
                window.dispatchEvent(new Event('scroll'));
            });
		},
        updated() {
            this.renderMathJax()  
        },
		methods:{
            async renderMathJax() {
                if (window.MathJax && window.MathJax.typesetPromise) {
                try {
                    await window.MathJax.typesetPromise();
                } catch (err) {
                    console.error('MathJax typesetting failed:', err);
                }
                }
            },
            // renderMathJax() {
            //     if (window.MathJax) {
            //         window.MathJax.typesetPromise(); // 重新渲染所有公式
            //     }
            // },
            // 新增校验方法
            handleStartInput(val, field) {
                // 移除非数字字符
                let num = val.replace(/[^\d]/g, '')
                num = num === '' ? '' : Math.min(100, Math.max(1, num))
                this[field] = num.toString()
                // 触发结束值的校验
                if (this.endedfscore) this.isValidEnd = this.endedfscore >= num
            },
            handleEndInput(val, field) {
                // 移除非数字字符
                let num = val.replace(/[^\d]/g, '')
                num = num === '' ? '' : Math.min(100, Math.max(1, num))
                this[field] = num.toString()
                // 触发开始值的校验
                if (this.startdfscore) this.isValidStart = this.startdfscore <= num
            },
            handleEndChange(val){
                if(this.rateLeft){
                    this.selectboxlist()
                }else{
                    this.$message.error('请选择开始得分率')
                }
                
            },
            handleStartChange(val){
                this.selectboxlist()
            },
            questiontypeChange(){
                this.selectboxlist()
            },
            answerclick(index){
                this.questionarrylist[index].questionIshow=!this.questionarrylist[index].questionIshow
                this.answerclickindex=index
                this.$nextTick(() => {
                    const selector = `.questionbox:nth-child(${index + 1}) .boxulxd`;
                    const element = document.querySelector(selector);
                    if (element) {
                        // 方案1：直接滚动到元素
                        element.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                        
                        // 方案2：自定义偏移（如需）
                        // const offset = element.getBoundingClientRect().top + window.scrollY - 100;
                        // window.scrollTo({ top: offset, behavior: 'smooth' });
                    }
                });
            },
            scoreclick(index){
                this.questionarrylist[index].questionScore=!this.questionarrylist[index].questionScore
                this.scoreclickindex=index
                this.$nextTick(() => {
                    const selector = `.questionbox:nth-child(${index + 1}) .boxulxd`;
                    const element = document.querySelector(selector);
                    if (element) {
                        // 方案1：直接滚动到元素
                        element.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                        
                        // 方案2：自定义偏移（如需）
                        // const offset = element.getBoundingClientRect().top + window.scrollY - 100;
                        // window.scrollTo({ top: offset, behavior: 'smooth' });
                    }
                });
            },
            // 获取题库
            questionbank(){
                let subjectid={
                    examCourseId:this.$route.query.courseid,
                }
                get('/work/questionids',subjectid).then(uuid=>{
                    // //console.info(uuid)
                    if(uuid.code==200){
                        let obj={
                            questionUUids:uuid.data
                        }
                        questionlist('/system/question/info/list/ids',obj).then(res => {
                            // //console.info(res)
                            if(res.code==200){
                                this.difficultylist = [...new Set(res.data
                                    .map(item => item.difficulty)  // 提取difficulty字段
                                    .filter(Boolean)               // 过滤空值
                                )]
                                // 创建第一个数据集
                                const questions = res.data.map(item => ({
                                    ...item,
                                    questionIshow: false, // 添加新参数
                                    questionScore:false
                                }))
                                this.questionnewlist = questions
                                this.contactarrayclick(questions)
                            }
                        })
                    }
                })
            },
            selectboxlist(){
                let objs={
                    classId:this.$route.query.classId,
                    questionId:0,
                    rateLeft:this.rateLeft?this.rateLeft:undefined,
                    rateRight:this.rateRight?this.rateRight:undefined,
                    questionTypeName:this.questionTypeName?this.questionTypeName:undefined,
                }
                questionlistscoreuuid(`/api/score/error-distribution-detail/list/${this.$route.query.examId}`, objs)
                .then(scoreRes => {
                    if(scoreRes.code === 200) {
                        this.questionarrylist =  this.mergeData(scoreRes.data, this.questionnewlist)
                        // 新增：更新sessionStorage为最新数据
                        sessionStorage.setItem('questionarrylist', JSON.stringify(this.questionnewlist))
                    }
                })
            },
            // 过滤合并数组
            contactarrayclick(content){
                let objs={
                        classId:this.$route.query.classId,
                        questionId:0,
                        rateLeft:this.rateLeft?this.rateLeft:undefined,
                        rateRight:this.rateRight?this.rateRight:undefined,
                        questionTypeName:this.questionTypeName?this.questionTypeName:undefined,
                }
                questionlistscoreuuid(`/api/score/error-distribution-detail/list/${this.$route.query.examId}`, objs)
                .then(scoreRes => {
                    if(scoreRes.code === 200) {
                        this.questionarrylist =  this.mergeData(scoreRes.data,content)
                        sessionStorage.setItem('questionarrylist', JSON.stringify(this.questionarrylist))
                    }
                })
            },
            mergeData(data1, data) {
                //console.info('data1', data1)
                // return false
                if (!data1 || data1.length === 0 || !data || data.length === 0) {
                        return [];
                    }

                const questionDataMap = new Map();
                data1.forEach(item => {
                    if (!questionDataMap.has(item.questionUUid)) {
                        questionDataMap.set(item.questionUUid, {
                            questionInfo: [],
                            details: []  // 改为数组形式，和questionInfo保持同样结构
                        });
                    }
                    // 存储questionInfo和details
                    questionDataMap.get(item.questionUUid).questionInfo.push({
                        ...item.questionInfo,
                        questionNum: item.questionNum
                    });
                    questionDataMap.get(item.questionUUid).details.push(item.details);
                });

                // Recursive function to process each item
                function processItem(item) {
                    const uuid = item.uuid;
                    
                    // If this UUID has data in our map
                    if (questionDataMap.has(uuid)) {
                        const matchedData = questionDataMap.get(uuid);
                        //console.info('matchedData',matchedData)
                        item.questionInfo = matchedData.questionInfo;
                        item.details = matchedData.details; // 设置details数组
                        item.questionNum = matchedData.questionInfo[0].questionNum || ''; 
                        questionDataMap.delete(uuid);
                    } else {
                        item.questionInfo = [];
                        item.details = []; // 初始化为空数组
                        item.questionNum = ''; // 初始化外层questionNum
                    }

                    // Process children if they exist
                    if (item.children && item.children.length > 0) {
                        item.children.forEach(child => {
                            processItem(child);
                        });
                        
                        // 合并questionInfo
                        if (item.children.some(child => child.questionInfo && child.questionInfo.length > 0)) {
                            item.questionInfo = item.children.reduce((acc, child) => {
                                if (child.questionInfo && child.questionInfo.length > 0) {
                                    return acc.concat(child.questionInfo);
                                }
                                return acc;
                            }, []);
                        }
                        
                        // 以相同逻辑合并details
                        if (item.children.some(child => child.details && child.details.length > 0)) {
                            item.details = item.children.reduce((acc, child) => {
                                if (child.details && child.details.length > 0) {
                                    return acc.concat(child.details);
                                }
                                return acc;
                            }, []);
                        }
                    }
                }

                // Process each item in the main data array
                data.forEach(item => {
                    processItem(item);
                });
                // 修改排序逻辑为使用外层questionNum
                const sortedData = [...data].sort((a, b) => {
                    // 提取a的数字部分
                    const numA = parseInt(a.questionInfo[0].questionNum.match(/\d+/)[0] || 0)
                    // 提取b的数字部分
                    const numB = parseInt(b.questionInfo[0].questionNum.match(/\d+/)[0] || 0)
                    
                    return numA - numB;
                });

                //console.info(sortedData)
                return sortedData;
               
                // return data;
                // return sortedQuestions
               
            },  
            getQuestionNumber(question) {
                const questionNum = question.questionInfo[0].questionNum || '';
                // 匹配数字部分（如 "单选题-1" 提取 1）
                const match = questionNum.match(/-(\d+)$/);
                return match ? parseInt(match[1], 10) : 0;
            }
		},
		components:{navTop,empty},
        beforeDestroy() {
            sessionStorage.removeItem('questionarrylist')
        }
	}
</script>

<style scoped>
	.main{
		width:100vw;
		height:100vh;
		background: #F4F7FD;
		overflow-x:hidden;
		overflow-y:auto;
	}
	.header {
	  background-color: #f8f8f8;
	  text-align: center;
	  transition: all 0.3s ease; /* 添加过渡效果 */
	}
	
	.sticky {
	  position: fixed;
	  top: 0;
	  left: 0;
	  right: 0;
	  z-index: 100;
	  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); /* 吸顶时添加阴影 */
	}
    .searchlist{
		box-sizing: border-box;
		width:auto;
		display: flex;
		justify-content: space-between;
		height: 54px;
		background: #FFFFFF;
		border-radius: 10px;
		padding:0 24px;
		align-items: center;
		margin:0 40px 0;
	}
	.searchlist a{
		display: block;
		color:#557292;
		font-size:14px;
		width:100px;
		text-align: center;
		position: relative;
		line-height:52px;
	}
	.searchlist a:hover,.searchlist a.hover{
		color:#295CFF;
	}
	.searchlist a:hover::after,.searchlist a.hover::after{
		content:'';
		width: 24px;
		height: 4px;
		background: #295CFF;
		border-radius: 2px;
		position: absolute;
		left:50%;
		transform: translateX(-50%);
		bottom:0;
	}
    .searchlist .el-select{
		width:144px;
        margin-right:24px;
	}
	.searchlist >>> .el-input__inner{
		width: 144px;
		border-radius: 10px;
		height:35px;
		font-size:14px;
	}
	.searchlist >>> .el-input__icon{
		line-height:35px;
	}
    .searchlist .elinput >>> .el-input__inner{
        width:80px;
        border:solid 1px #D8E4F0
    }
    .elinput{
        margin-right:24px;
    }
    .titledata{
        font-size:14px;
        color:#2A303B;
    }
    .titledata i{
        display: inline-block;
        width: 68px;
        height: 24px;
        background: #295CFF;
        border: 1px solid #295CFF;
        border-radius: 6px;
        color:#fff;
        font-size:12px;
        line-height:24px;
        text-align: center;
        font-style: normal;
        margin-right:10px;
    }
    .questionbox{
		box-sizing: border-box;
		width:auto;
		background: #FFFFFF;
		border-radius: 10px;
		padding:15px 0 0;
		align-items: center;
		margin:14px 40px 0;
        position:relative
	}
	.questionbox a{
		display: block;
		color:#557292;
		font-size:14px;
		width:100px;
		text-align: center;
		position: relative;
		line-height:52px;
	}
	.questionbox a:hover,.questionbox a.hover{
		color:#295CFF;
	}
	.questionbox a:hover::after,.questionbox a.hover::after{
		content:'';
		width: 24px;
		height: 4px;
		background: #295CFF;
		border-radius: 2px;
		position: absolute;
		left:50%;
		transform: translateX(-50%);
		bottom:0;
	}
    .questionbox .el-select{
		width:144px;
        margin-right:24px;
	}
	.questionbox >>> .el-input__inner{
		width: 144px;
		border-radius: 10px;
		height:35px;
		font-size:14px;
	}
	.questionbox >>> .el-input__icon{
		line-height:35px;
	}
    .questionbox .elinput >>> .el-input__inner{
        width:80px;
        border:solid 1px #D8E4F0
    }
    .titlebox{
        height:45px;
        background: #295CFF;
        border-radius: 0 100px 100px 0;
        font-size:18px;
        color:#fff;
        position:absolute;
        left:-10px;
        top:0px;
        font-weight:500;
        line-height:45px;
        padding:0 20px;
        display:flex;
        justify-content: space-between;
        align-items: center;
    }
    .titlebox::after{
        content: '';
        width:10px;
        height:10px;
        position: absolute;
        left:0px;
        bottom:-10px;
        background:url('../../assets/image/school/sjd.jpg') no-repeat;
    }
    .questionscore{
        font-size:16px;
        color:#5B6371;
        font-style:normal;
        padding-top:8px; 
    }
    .questionscore i{
        display: inline-block;
        color:#2A303B;
        font-style:normal
    }
    .boxcenterbutton{
        display: flex;
        justify-content: right;
        border-radius:0 0 10px 10px;
        padding:0 15px 0 0;
    }
    .boxcenterbutton span{
        display: inline-block;
        width: 104px;
        height: 34px;
        background: #295CFF;
        border-radius: 10px;
        text-align: center;
        line-height:34px;
        font-size:14px;
        color:#fff;
        margin-left:14px;
        cursor: pointer;
    }
    .boxcenterbutton span i{
        display: inline-block;
        margin-left:5px;
        transition: all .3s;
    }
    .boxcenterbutton span i.hover{
        transform: rotate(180deg);
    }
    .boxcenterbutton span:nth-child(2){
        background:none;
        border:solid 1px #295CFF;
        color:#295CFF
    }
    .boxulxd{
        padding:0 14px;
    }
    .boxulxd li{
        box-sizing: border-box;
        width:100%;
        background:rgb(247, 249, 255);
        border-radius: 6px;
        margin-bottom:10px;
        color:Rgb(114, 121, 133);
        font-size:14px;
        line-height:30px;
        padding:0 10px;
    }
    /* 在style区域添加 */
.no-spin::-webkit-outer-spin-button,
.no-spin::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
.no-spin {
    -moz-appearance: textfield;
}
</style>